package com.zhangyu.shadow.core.delegate.web.client;

import android.graphics.Bitmap;
import android.os.Handler;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.zhangyu.shadow.core.app.ConfigType;
import com.zhangyu.shadow.core.app.Shadow;
import com.zhangyu.shadow.core.delegate.IPageLoadListener;
import com.zhangyu.shadow.core.delegate.web.WebDelegate;
import com.zhangyu.shadow.core.delegate.web.route.Router;
import com.zhangyu.shadow.core.ui.loader.ShadowLoader;
import com.zhangyu.shadow.core.util.log.ShadowLogger;
import com.zhangyu.shadow.core.util.storage.ShadowPreference;

/**
 * @author zhangyu
 * @date 2017/11/13
 */

public class WebViewClientImpl extends WebViewClient {
    private final WebDelegate mWebDelegate;
    private IPageLoadListener mIPageLoadListener;
    private final static Handler HANDLER = Shadow.getHandler();

    public void setIPageLoadListener(IPageLoadListener IPageLoadListener) {
        mIPageLoadListener = IPageLoadListener;
    }

    public WebViewClientImpl(WebDelegate webDelegate) {
        mWebDelegate = webDelegate;
    }

    //获取浏览器cookie
    private void syncCookie() {
        final CookieManager cookieManager = CookieManager.getInstance();
        //这里的Cookie和api请求里的是不一样的,这个在网页不可见
        final String webHost = Shadow.getConfiguration(ConfigType.WEB_HOST);
        if (webHost != null) {
            if (cookieManager.hasCookies()) {
                final String cookieStr = cookieManager.
                        getCookie((String) Shadow.getConfiguration(ConfigType.WEB_HOST));
                if (cookieStr != null && !cookieStr.isEmpty()) {
                    ShadowPreference.addCustomAppProfile("cookie", cookieStr);
                }
            }
        }
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        ShadowLogger.d("shouldOverrideUrlLoading", url);
        return Router.getInstance().handleWebUrl(mWebDelegate, url);
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        if (mIPageLoadListener != null) {
            mIPageLoadListener.onLoadStart();
        }
        ShadowLoader.showLoading(view.getContext());
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        syncCookie();
        if (mIPageLoadListener != null) {
            mIPageLoadListener.onLoadEnd();
        }
        HANDLER.post(new Runnable() {
            @Override
            public void run() {
                ShadowLoader.stopLoading();
            }
        });
    }
}
